#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen@163.com
@file: handle_utils.py
@time: 2023/10/26 15:30
@desc:
"""
import functools

import jwt

from backend.tvadmin.system.models.permission import User


def authenticated_async(method):
    @functools.wraps(method)
    async def wrapper(self, *args, **kwargs):
        Authorization = self.request.headers.get("Authorization", None)
        if Authorization:
            # 对token过期进行异常捕捉
            try:
                # 从 token 中获得我们之前存进 payload 的用户id
                send_data = jwt.decode(Authorization, self.settings["secret_key"], leeway=self.settings["jwt_expire"],
                                       options={"verify_exp": True})
                user_id = send_data["id"]
                # 从数据库中获取到user并设置给_current_user
                try:
                    user = await self.application.objects.get(User, id=user_id)
                    self._current_user = user
                    # 此处需要使用协程方式执行 因为需要装饰的是一个协程
                    await method(self, *args, **kwargs)
                except User.DoesNotExist as e:
                    self.set_status(401)

            except jwt.ExpiredSignatureError as e:
                self.set_status(401)
        else:
            self.set_status(401)
        self.finish({})
    return wrapper
